package com.yf.exam.modules.trainingarchives.trainingclassschedule.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.yf.exam.common.entity.Result;
import com.yf.exam.common.vo.PullDownListVO;
import com.yf.exam.common.vo.TraingTypeAndDescVO;
import com.yf.exam.core.api.ApiRest;
import com.yf.exam.core.api.controller.BaseController;
import com.yf.exam.core.api.dto.BaseIdReqDTO;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.core.exception.ServiceException;
import com.yf.exam.core.utils.excel.ExportExcel;
import com.yf.exam.core.utils.excel.ImportExcel;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.dto.export.TrainingClassScheduleExportDTO;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.dto.req.TrainingClassScheduleReqDTO;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.dto.resp.TrainingClassScheduleRespDTO;
import com.yf.exam.modules.trainingarchives.trainingclassschedule.service.ITrainingClassScheduleService;
import com.yf.exam.modules.trainingarchives.worktype.dto.resp.OrgWorkTypeRespDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 培训班课程安排表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-12-29
 */
@Api(tags={"培训班课程安排"})
@RestController
@RequestMapping("/training-class-schedule")
@Slf4j
public class TrainingClassScheduleController extends BaseController {

    @Resource
    private ITrainingClassScheduleService trainingClassScheduleService;

    /**
     * 新增培训班课程
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增培训班课程")
    public Result<Boolean> add(@RequestBody TrainingClassScheduleReqDTO reqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TrainingClassScheduleController.add.TrainingClassScheduleReqDTO:{}", JSON.toJSONString(reqDTO));
            }
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getTrainingClassInfoId()), "培训班id不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getTeacherName()), "授课教师不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getEducation()), "学历不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getMajor()), "专业不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getTitle()), "职称不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getCourse()), "培训课程内容不能为空!");
            Preconditions.checkNotNull(reqDTO.getHours(), "课时不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getQualificationNumber()), "教师资格证编号不能为空!");
            return Result.ok(trainingClassScheduleService.add(reqDTO));
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.add.error:{}", e.getMessage(), e);
            return Result.faild("新增培训班课程失败!");
        }
    }


    /**
     * 删除项目
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除培训班课程")
    public Result<Boolean> delete(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TrainingClassScheduleController.delete.elProjectReqDTO:{}", JSON.toJSONString(baseIdReqDTO));
            }
            Preconditions.checkNotNull(baseIdReqDTO.getId(), "培训班课程id不能为空!");
            Boolean result = trainingClassScheduleService.deleteById(baseIdReqDTO.getId());
            return Result.ok(result);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.delete.error:{}", e.getMessage(), e);
            return Result.faild("删除培训班课程失败!");
        }

    }

    /**
     * 更新项目
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新培训班课程")
    public Result<Boolean> update(@RequestBody TrainingClassScheduleReqDTO reqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TrainingClassScheduleController.update.dto:{}", JSON.toJSONString(reqDTO));
            }
            Preconditions.checkNotNull(reqDTO.getId(), "培训班课程id不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getTeacherName()), "授课教师不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getEducation()), "学历不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getMajor()), "专业不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getTitle()), "职称不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getCourse()), "培训课程内容不能为空!");
            Preconditions.checkNotNull(reqDTO.getHours(), "课时不能为空!");
            Preconditions.checkArgument(!StringUtils.isBlank(reqDTO.getQualificationNumber()), "教师资格证编号不能为空!");
            Boolean result = trainingClassScheduleService.updateTrainingclassschedule(reqDTO);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.update.error:{}", e.getMessage(), e);
            return Result.faild("更新培训班课程失败");
        }
    }

    /**
     * 分页查找
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @PostMapping("/paging")
    public Result<IPage<TrainingClassScheduleRespDTO>> paging(@RequestBody PagingReqDTO<TrainingClassScheduleReqDTO> reqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TrainingClassScheduleController.paging.dto:{}", JSON.toJSONString(reqDTO));
            }
            //分页查询并转换
            IPage<TrainingClassScheduleRespDTO> page = trainingClassScheduleService.paging(reqDTO);
            return Result.ok(page);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.paging.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }

    /**
     * 培训班课程详情
     */
    @PostMapping("/detail")
    @ApiOperation(value = "获取培训班课程详情")
    public Result<TrainingClassScheduleRespDTO> detail(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            if (log.isInfoEnabled()) {
                log.info("TrainingClassScheduleController.detail.baseIdReqDTO:{}", JSON.toJSONString(baseIdReqDTO));
            }
            Preconditions.checkArgument(!(baseIdReqDTO.getId() == null), "培训班课程ID不能为空!");
            return Result.ok(trainingClassScheduleService.getDetail(baseIdReqDTO));
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.detail.error:{}", e.getMessage(), e);
            return Result.faild("查询培训班课程详情失败!");
        }
    }

    /**
     * 下载导入试题数据模板
     */
    @ResponseBody
    @RequestMapping(value = "/import/template",method = {RequestMethod.POST})
    @ApiOperation(value = "获取培训班课程导入模板")
    public ApiRest importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "培训班课程导入模板.xlsx";
            List<TrainingClassScheduleExportDTO> list = Lists.newArrayList();

            new ExportExcel("培训班课程数据", TrainingClassScheduleExportDTO.class, 2).setDataList(list).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return super.failure("导入模板下载失败！失败信息："+e.getMessage());
        }
    }


    /**
     * 导入培训班课程信息Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/import/questions",method = {RequestMethod.POST})
    @ApiOperation(value = "导入培训班课程信息Excel")
    public ApiRest importFileNew(@RequestParam("id") String id,@RequestParam("file") MultipartFile file) {

        try {

            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<TrainingClassScheduleExportDTO> list = ei.getDataList(TrainingClassScheduleExportDTO.class);

            // 校验数据
            this.checkExcel(list);

            // 导入数据条数
            trainingClassScheduleService.importExcel(id,list);

            // 导入成功
            return super.success();

        } catch (IOException e) {

        } catch (InvalidFormatException e) {

        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        }

        return super.failure();
    }


    /**
     * 校验Excel
     * @param list
     * @throws Exception
     */
    private void checkExcel(List<TrainingClassScheduleExportDTO> list) throws ServiceException {
        // 约定第三行开始导入
        int line = 3;
        StringBuffer sb = new StringBuffer();
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException(1, "您导入的数据似乎是一个空表格！");
        }
        for (TrainingClassScheduleExportDTO item : list) {
            if (item.getTeacherName().equals("授课教师")) {
                line++;
                continue;
            }
            if (item.getTeacherName() == null) {
                sb.append("第" + line + "行，授课教师不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getEducation())) {
                sb.append("第" + line + "行，学历不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getGender())) {
                sb.append("第" + line + "行，性别不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getJobType())) {
                sb.append("第" + line + "行，全职/兼职不能为空!<br>");
            }
            if (StringUtils.isBlank(item.getMajor())) {
                sb.append("第" + line + "行，专业不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getTitle())) {
                sb.append("第" + line + "行，职称不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getCourse())) {
                sb.append("第" + line + "行，培训课程内容不能为空!<br>");
            }
            if (item.getTrainingTime() == null) {
                sb.append("第" + line + "行，培训日期不能为空!<br>");
            }
            if (StringUtils.isEmpty(String.valueOf(item.getHours()))) {
                sb.append("第" + line + "行，课时不能为空!<br>");
            }
            if (StringUtils.isEmpty(item.getQualificationNumber())) {
                sb.append("第" + line + "行，教师资格证编号不能为空!<br>");
            }
            line++;
        }
        // 存在错误
        if (!"".equals(sb.toString())) {
            throw new ServiceException(1, sb.toString());
        }
    }

    /**
     * 获取列表
     * @return
     */
    @ApiOperation(value = "获取列表")
    @PostMapping("/getList")
    public Result<List<TrainingClassScheduleRespDTO>> getList() {
        try {
            //查找列表
            List<TrainingClassScheduleRespDTO> respDTOList = trainingClassScheduleService.getList();
            return Result.ok(respDTOList);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.paging.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }

    /**
     * 获取下拉列表
     * @return
     */
    @ApiOperation(value = "获取下拉列表")
    @PostMapping("/getPullDownList")
    public Result<List<PullDownListVO>> getPullDownList(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            //查找列表
            List<PullDownListVO> respDTOList = trainingClassScheduleService.getPullDownList(baseIdReqDTO.getId());
            return Result.ok(respDTOList);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.paging.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }


    /**
     * 下拉框列表
     * @return
     */
    @ApiOperation(value = "培训班课程下拉框列表")
    @PostMapping("/list")
    public Result<List<PullDownListVO>> getListById(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            //分页查询并转换
            List<PullDownListVO> page = trainingClassScheduleService.getListById(baseIdReqDTO.getId());
            return Result.ok(page);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.getListById.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }


    /**
     * 根据培训id查询初训复训
     * @return
     */
    @ApiOperation(value = "根据培训id查询初训复训")
    @PostMapping("/getDesc")
    public Result<TraingTypeAndDescVO> getDesc(@RequestBody BaseIdReqDTO baseIdReqDTO) {
        try {
            //分页查询并转换
            TraingTypeAndDescVO traingTypeAndDescVO = trainingClassScheduleService.getDesc(baseIdReqDTO.getId());
            return Result.ok(traingTypeAndDescVO);
        } catch (Exception e) {
            log.error("TrainingClassScheduleController.getDesc.error:{}", e.getMessage(), e);
            return Result.faild("查询失败");
        }
    }
}
